
var wsClient = null;
var sessionId = genUUID();
//连接服务
function connWs(wsServer, onSucess, onError) {
	var client = new WsClient({
	    login: wsAccount,
	    passwd: wsSecret,
	    socketUrl: wsServer,
	    sessid: sessionId,
	    onmessage: function(e) {
			handleMsg(e.eventData);
	    },
	    onWSConnect: function(o) {
			client.call('login', {});
	    	if (onSucess) onSucess();
	    },
	    onWSLogin: function(success) {
	    },
	    onWSError: function(e) {
	    	if (onError) onError(e);
	    },
	    onWSClose: function(success) {
	    }
	});
	return client;
}

//检查登录
function checkLogin() {
	if ($('.user-panel').length > 0) {
		initMsg('我已成功登录会员');
	} else {
		initMsg('你好');
	}
	sendMsg();
}

//初始化消息
function initMsg(msg) {
	$('#txt-msg').attr('data-content', '');
	$("[data-toggle='popover']").unbind('popover');
	$("[data-toggle='popover']").popover({html : true});
	$('#txt-msg').click();
	$('#txt-msg').attr('refer', '');
	$('#txt-msg').attr('type', 'text');
	$('#txt-msg').attr('placeholder', '请输入消息');
	$('#txt-msg').val(msg);
}

//处理消息
function procMsg(msg, txt = '') {
	var pattern = /[，。！？：；、,.!?:;]/;
	var msgs = msg.split(pattern);
	if (msgs.length <= 1) return;
	var txts = txt.split(pattern);
	msgs[0] = txts[txts.length - 1] + msgs[0];
	var len = msgs.length;
	for (var i = 0; i < len - 1; i++) {
		var sub = msgs[i] + ",";
		//console.log(sub);
		if (liveClient) {
		    var params = {
		        body: sub
		    };
		    liveClient.call("message", params, function(e) {
		    }, function(e) {
		    });
		}
	}
}

//点击消息
function clickMsg(obj) {
	var txt = $(obj).text();
	var ele = $('[aij="' + txt + '"]');
	var contents = $('document.body');
	if (ele.length == 0) {
		contents = $('#content-main iframe:visible').contents();
		if (contents.length > 0) {
			ele = contents.last().find('[aij="' + txt + '"]');
		}
	}
	if (ele.length == 0) {
		contents = $('.layui-layer-iframe iframe:visible').contents();
		if (contents.length > 0) {
			ele = contents.last().find('[aij="' + txt + '"]');
		}
	}
	//console.log(ele);
	if (ele.length > 0) {
		var tagName = ele.prop("tagName").toLowerCase();
		var tagType = ele.attr('type');
		if (tagName == 'a' || tagName == 'button' || (tagName == 'input' && tagType == "button")) {
			ele.click();
			if ($('.layui-layer-dialog').length > 0 && $('.layui-layer-dialog .layui-icon-success').length == 0) return;
			initMsg('我要' + txt);
			sendMsg();
		} else if (tagName == 'form') {
			initMsg('我要' + txt);
			sendMsg();
		} else if (tagName == 'select') {
			var content = '<select refer="' + ele.attr('name') + '" class="form-control">' + ele.html() + '</select>';
			$('#txt-msg').attr('data-content', content);
			$("[data-toggle='popover']").unbind('popover');
			$("[data-toggle='popover']").popover({html : true});
			$('#txt-msg').attr('refer', txt);
			$('#txt-msg').attr('placeholder', '请' + txt);
			$('#txt-msg').click();
		} else if (tagName == 'input') {
			if (tagType == "radio" || tagType == "checkbox") {
				var name = ele.attr('name');
				var content = '';
				ele.each(function() {
					var eva = $(this).attr('value');
					if (typeof(eva) == 'undefined') {
						content += '<input type="' + tagType + '" name="aij-' + name + '" refer="' + name + '" class="form-inline"/>';
					} else {
						content += '<input type="' + tagType + '" value="' + eva + '" name="aij-' + name + '" refer="' + ele.attr('name') + '" class="form-inline"/>';
					}
					var eid = $(this).attr('id');
					var label = contents.last().find('label[for="' + eid + '"]').text();
					content += ' <label>' + label + '</label>';
				});
				$('#txt-msg').attr('data-content', content);
				$("[data-toggle='popover']").unbind('popover');
				$("[data-toggle='popover']").popover({html : true});
				$('#txt-msg').attr('refer', txt);
				$('#txt-msg').attr('placeholder', '请' + txt);
				$('#txt-msg').click();
			} else {
				$('#txt-msg').attr('data-content', '');
				$('#txt-msg').attr('type', tagType);
				$('#txt-msg').val(ele.val());
			}
			$("[data-toggle='popover']").unbind('popover');
			$("[data-toggle='popover']").popover({html : true});
			$('#txt-msg').attr('refer', txt);
			$('#txt-msg').attr('placeholder', '请' + txt);
			$('#txt-msg').click();
		}
	}
}

//解析消息
function parseMsg(msg) {
	if (msg.indexOf(']') >= 0) {
		msg = msg.replaceAll('[', '<a href="javascript:;" onclick="clickMsg(this)">');
		msg = msg.replaceAll(']', '</a>');
	}
	return msg;
}

//接收消息
function recvMsg(msg, id) {
    var msgHead = "<b>AI</b>";
    if ($('#msg'+id).length > 0) {
    	var txt = $('#msg'+id).html();
    	$('#msg'+id).html(txt + msg);
    	procMsg(msg, txt);
    } else {
	    var content = '<div id="msg' + id + '" class="msg-right">' + msgHead + ': ' + msg + '</div>';
	    $('#msg-div').append(content);
    	procMsg(msg);
    }
    if (msg == '') {
    	var txt = $('#msg'+id).html();
    	$('#msg'+id).html(parseMsg(txt));
	    $("#msg-div").height($("#msg-div div:last").height() - 4);
    	//saveMsg(txt, 'aij', 0);
    }
    $("#msg-div").scrollTop($("#msg-div")[0].scrollHeight);
}

//处理消息
function handleMsg(data) {
	if (data.method == "message") {
		recvMsg(data.params.body, data.id);
	}
	if (data.method == "word") {
		setTimeout(function(){
    		$('#word-div').text(data.params.body);
    	}, liveDelay);
	}
}

//发送消息
function sendMsg() {
    if (!wsClient) {
    	wsClient = connWs(wsServer, function(e) {
    		sendMsg();
    	}, function(e) {
    		wsClient = connWs(wsServer);
    	});
    	return;
    }
    var refer = $('#txt-msg').attr('refer');
    if (refer) {
		var ele = $('[aij="' + refer + '"]');
		var contents = $('document.body');
		if (ele.length == 0) {
			contents = $('#content-main iframe:visible').contents();
			if (contents.length > 0) {
				ele = contents.last().find('[aij="' + refer + '"]');
			}
		}
		if (ele.length == 0) {
			contents = $('.layui-layer-iframe iframe:visible').contents();
			if (contents.length > 0) {
				ele = contents.last().find('[aij="' + refer + '"]');
			}
		}
		var content = $('#txt-msg').attr('data-content');
		if (content) {
			var tagName = ele.prop("tagName").toLowerCase();
			var name = ele.attr('name');
			if (tagName == 'select') {
				ele.val($('[refer="' + name + '"]').val());
			} else {
				$('[refer="' + name + '"]').each(function() {
					var eva = $(this).attr('value');
					var eck = $(this).is(':checked');
					if (typeof(eva) == 'undefined') {
						contents.last().find('input[name="' + name + '"]').attr('checked', eck);
					} else {
						contents.last().find('input[name="' + name + '"][value="' + eva + '"]').attr('checked', eck);
					}
				});
			}
		} else {
			ele.val($('#txt-msg').val());
		}
		initMsg('我已' + refer);
    }
    var msg = $('#txt-msg').val();
    if (!msg) {
        $('#txt-msg').focus();
        return;
    }
    var params = {
        body: msg
    };
    var webClient = wsClient.socketReady() ? wsClient : liveClient;
    if (webClient) {
	    webClient.call("message", params, function(e) {
    		//saveMsg(msg, 'aij', 0, true);
		    var msgHtml = '<div class="msg-left"><b>我</b>: ' + msg + '</div>';
		    $('#msg-div').append(msgHtml);
	    	$("#msg-div").height($("#msg-div div:last").height() - 2);
		    $("#msg-div").scrollTop($("#msg-div")[0].scrollHeight);
		    $('#txt-msg').val("");
	    }, function(e) {
	    });
    }
}

//保存消息
function saveMsg(msg, from, count, self) {
	var prefix = "ruoyi-";
	var counts = localStorage.getItem(prefix + "icall-msg-counts");
	counts = counts ? JSON.parse(counts) : new Object();
    var pos = from.indexOf('@');
    from = pos < 0 ? from : from.substring(0, pos);
    counts[from] = counts[from] ? counts[from] + count : count;
	localStorage.setItem(prefix + "icall-msg-counts", JSON.stringify(counts));
	var msgs = localStorage.getItem(prefix + "icall-msg-" + from);
	msgs = msgs ? JSON.parse(msgs) : new Array();
	var msg = self ? {body: msg} : {body: msg, from: from};
	msgs.push(msg);
	localStorage.setItem(prefix + "icall-msg-" + from, JSON.stringify(msgs));
	return counts[from];
}

//加载消息
function loadMsg(from) {
	var prefix = "ruoyi-";
	var counts = localStorage.getItem(prefix + "icall-msg-counts");
	counts = counts ? JSON.parse(counts) : new Object();
	if (!from) return counts;
	var msgs = localStorage.getItem(prefix + "icall-msg-" + from);
	msgs = msgs ? JSON.parse(msgs) : new Array();
	counts[from] = 0;
	localStorage.setItem(prefix + "icall-msg-counts", JSON.stringify(counts));
	return msgs;
}

//显示消息
function showMsg() {
    var msgs = loadMsg('aij');
    var content = '';
    for (const msg of msgs) {
    	if (msg.from) {
	    	content += '<div style="text-align:right;">' + friend + ': ' + parseMsg(msg.body) + '</div><br/>';
	    } else {
	    	content += '<div>我: ' + parseMsg(msg.body) + '</div><br/>';
	    }
    }
    $("#msg-div").html(content);
    $("#msg-div").scrollTop($("#msg-div")[0].scrollHeight);
}

var liveClient = null;
var flvPlayer = null;
var flvAudio = null;
//开始播放
function startPlayer() {
	liveClient = connWs(pushServer);
    liveUrl = liveServer+"video-"+sessionId+".flv";
    console.log(liveUrl);
    flvPlayer = mpegts.createPlayer({type: 'flv', url: liveUrl, isLive: true, enableStashBuffer: false});
	flvPlayer.attachMediaElement(document.getElementById('you-video'));
	flvPlayer.load();
	flvPlayer.play();
    audioUrl = liveServer+"audio-"+sessionId+".flv";
    console.log(audioUrl);
    flvAudio = mpegts.createPlayer({type: 'flv', url: audioUrl, isLive: true, enableStashBuffer: false});
	flvAudio.attachMediaElement(document.getElementById('you-audio'));
	flvAudio.load();
	flvAudio.play();
}

//停止播放
function stopPlayer() {
	liveClient.closeSocket();
	flvPlayer.pause();
    flvPlayer.destroy();
    flvPlayer = null;
	flvAudio.pause();
    flvAudio.destroy();
    flvAudio = null;
}

//视频开关
function openVideo() {
	if ($('#div-video').is(':hidden')) {
	    $('#msg-div').hide();
	    $('#div-video').show();
	    if (!flvPlayer) {
	    	startPlayer();
		}
	    $('#div-word').show();
	    $('#word-div').text("");
		$('#btn-video').val('关闭');
    } else {
	    $('#div-video').hide();
	    $('#msg-div').show();
        if (flvPlayer) {
        	stopPlayer();
        }
	    $('#div-word').hide();
		$('#btn-video').val('视频');
    }
}